package org.springframework.samples.petclinic.controllers;

import org.springframework.samples.petclinic.model.owner.Visit;
import org.springframework.ui.Model;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.Services.UserServices;
import org.springframework.samples.petclinic.model.owner.Owner;
import org.springframework.samples.petclinic.system.WebSecurityConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class UsrController {
	@Autowired
	private UserServices userServices;
//	public UsrController(UserServices userServices) {
//		this.userServices = userServices;
//	}
	@ModelAttribute
	//隐式key为"owner"
	public Owner setUser(HttpSession session){
		String accountName = (String) session.getAttribute(WebSecurityConfig.SESSION_KEY);
		return userServices.findByAccountName(accountName);
	}

	@GetMapping("/usr/checkMyPet")
	public String checkPets(Model model){
		/**pet数据已在执行ModelAttribute时被装入model*/
		return null;
	}
	@GetMapping("/usr/ownerHome")
	public String ownerHome(){
		return "ownerWelcome";
	}

	@GetMapping("/usr/editMyPet")
	public String editPets(){
		return null;
	}
	@PostMapping("/usr/editMyPet")
	public String updatePets(){

		return null;
	}
	@GetMapping("/usr/checkMyInfo")
	public String checkInfo(){
		/**pet数据已在执行ModelAttribute时被装入model*/
		return "owner/checkMyInfo";
	}

	@GetMapping("/usr/editMyInfo")
	public String editInfo(){
		/**pet数据已在执行ModelAttribute时被装入model*/
		return "editMyInfo";
	}

	@PostMapping("/usr/editedMyInfo")
	public String editedInfo(Owner editedOwner){
		userServices.updateOwner(editedOwner);
		return "redirect:/usr/checkMyInfo";
	}

	@GetMapping("/usr/checkMyVisit")
	public String checkVisits(@ModelAttribute Owner owner,Model model){
		List<Visit> visits = userServices.getVisits(owner.getId());
		model.addAttribute("visits",visits);
		return null;
	}

	@GetMapping("/usr/addMyVist")
	public String addVisit(){
		/**pet数据已在执行ModelAttribute时被装入model*/
		return null;
	}
	@PostMapping("/usr/addMyVisit")
	public String processAddVisitRequest(Visit visit, @ModelAttribute Owner owner, @RequestParam Integer petID){
		userServices.addVisit(visit,owner,petID);
		return "redirect:/usr/checkMyVisit";
	}
	@PostMapping("/usr/cancelMyVisit")
	public String cancelVisit(@RequestParam Integer visitID,@RequestParam Integer petID,Model model){
		userServices.cancelVisit(visitID,petID,(Owner)model.getAttribute("owner"));
		return "redirect:/usr/checkMyVisit";
	}
}
